package com.fast.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fast.configs.properties.UploadProperties;
import com.fast.constants.CommonConstants;
import com.fast.exception.BusinessException;
import com.fast.pojo.req.UploadFileRequest;
import com.fast.service.FilesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.service.impl.FilesServiceImpl
 * @description: TODO
 * @since 2024/6/22 1:39
 */
@Slf4j
@Service
public class FilesServiceImpl implements FilesService {
    @Resource
    private UploadProperties uploadProperties;
    @Resource
    private HttpServletRequest request;

    /**
     * 头像上传
     *
     * @param uploadFileRequest 上传的文件请求对象
     * @return 格式：resources/type/20240622.jpg
     */
    @Override
    public String upload(UploadFileRequest uploadFileRequest) {
        MultipartFile file = uploadFileRequest.getFile();
        if (file.isEmpty()) {
            log.warn("未上传文件");
            throw new BusinessException("未上传文件");
        }
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)) {
            log.warn("上传的文件原始名称为空");
            throw new BusinessException("上传的文件原始名称为空");
        }
        String module = uploadFileRequest.getModule();
        String relativePath = spliceRelativePath(originalFilename, module);
        doStoreFile(relativePath, file);
        return relativePath;
    }

    private void doStoreFile(String relativePath, MultipartFile file) {
        //E:/filesThatUpload/+resources/ type/ 20230523/ 123.jpg
        String localAbsPath = uploadProperties.getStaticDir() + relativePath;
        File destFile = new File(localAbsPath);
        try {
            //确保目录被创建
            FileUtils.forceMkdir(destFile.getParentFile());
        } catch (IOException e) {
            log.error("make dir error", e);
            throw new BusinessException("创建父级目录出错");
        }
        try {
            file.transferTo(destFile);
        } catch (Exception e) {
            log.error("store image or file error,filePath:{}", localAbsPath, e);
        }
        throw new BusinessException("存储文件出错");
    }

    /**
     * 拼接上传文件在本地存储的相对路径,格式如:resources/type/20230523/123.jpg
     *
     * @param originalfileName 原始文件名
     */
    private String spliceRelativePath(String originalfileName, String module) {
        String patternDate = DateUtil.format(LocalDateTime.now(), CommonConstants.UPLOAD_FDATE_FORMAT);
        String newFileName = reName(originalfileName);//relativePath:resources/type/20230523/123.jpg
        StringBuilder relativePath = new StringBuilder();
        relativePath.append(CommonConstants.RESOURCES_FPREFIX);
        // 校验模块名是否为空
        if (StrUtil.isNotBlank(module)) {
            relativePath.append(module).append(CommonConstants.SLASH);

        }
        relativePath.append(patternDate).append(newFileName);
        return relativePath.toString();
    }

    private String reName(String originalFilename) {
        String baseName = IdUtil.fastSimpleUUID();
        return baseName + CommonConstants.DOT + FilenameUtils.getExtension(originalFilename);
    }
}
